<?php

namespace app\tickets\controller;

use Aliyun\Api\Sms\Request\V20170525\SendSmsRequest;
use app\common\controller\Common;
use app\index\controller\Base;
use NativePay;
use QRcode;
use think\Db;
use think\Exception;
use think\Session;
use think\Validate;
use WxPayConfig;
use WxPayUnifiedOrder;


class Online extends Base
{

    /**
     * 轮询操作(查询订单是否已付款)
     * @author zhixuedong
     * @date 2021/1/26/026
     */
    public function showUnreadNews(){
        $common = new Common();


        try{
            $orderTable = "tickets_order";
            $where['id'] = $_POST['id'];
            $is_pay = $common->public_select($orderTable,$where)->value("is_pay");
            if($is_pay==2){
                $black['code'] = 0;
                $black['msg'] = "已付款";
            }else{
                $black['code'] = 2;
                $black['msg'] = "未付款";
            }

        }catch (Exception $e){
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return $black;
    }


    /**
     * 生成二维码
     * @author zhixuedong
     * @date 2021/1/25/025
     */
    public function qrcode(){
        error_reporting(E_ERROR);
        require_once ROOT_PATH.'extend/wxpay/example/phpqrcode/phpqrcode.php';
        $data = urlencode($_GET["data"]);
        $url = urldecode($data);
        QRcode::png($url);
    }


    //生成订单号
    public function generateNo(){
        $common = new Common();
        $current_date = date("Ymd");
        $thisWechat = Session::get("thisWechat");
        $where['uniacid'] = $thisWechat['id'];
        $where['currentDate'] = $current_date;
        $table = "tickets_order";
        $order_sn = $common->public_select($table,$where)->order("order_sn desc")->value('order_sn');
        if(empty($order_sn)){
            $order_sn = $current_date."00001";
        }else{
            $order_sn = $order_sn+1;
        }
        return $order_sn;
    }


    //发送短信
    public function sms($code,$phone){
        $current_date = date("Y-m-d");;
        //记录当天发送的数量
        $detail = Db::name("sms")->where(['phone'=>$phone,'current_date'=>$current_date])->find();
//        if($detail['count']>1){
//            throw new Exception("超出当天可发送的数量");
//        }
        if(empty($detail)){
            $data['phone'] = $phone;
            $data['current_date'] = $current_date;
            $data['count'] = 1;
            Db::name("sms")->insert($data);
        }else{
            Db::name("sms")->where(['phone'=>$phone,'current_date'=>$current_date])->setInc("count",1);
        }

        $common = new \app\api\controller\Common();
        require_once ROOT_PATH."extend/sms/api_sdk//vendor/autoload.php";//引入PHPExcel加载文件
        // 初始化SendSmsRequest实例用于设置发送短信的参数
        $request = new SendSmsRequest();

        //可选-启用https协议
        //$request->setProtocol("https");
        // 必填，设置短信接收号码
        $request->setPhoneNumbers($phone);
        // 必填，设置签名名称，应严格按"签名名称"填写，请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/sign
        $request->setSignName("鲸探");
        // 必填，设置模板CODE，应严格按"模板CODE"填写, 请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/template
        $request->setTemplateCode("SMS_190283810");
        // 可选，设置模板参数, 假如模板中存在变量需要替换则为必填项
        $request->setTemplateParam(json_encode(array(  // 短信模板中字段的值
            "code"=>$code,
        ), JSON_UNESCAPED_UNICODE));
        // 可选，设置流水号
        $request->setOutId("yourOutId");
        // 选填，上行短信扩展码（扩展码字段控制在7位或以下，无特殊需求用户请忽略此字段）
        $request->setSmsUpExtendCode("1234567");
        // 发起访问请求
        $acsResponse = $common->getAcsClient()->getAcsResponse($request);
        return $acsResponse;
    }

    /**
     * 生成订单
     * @author zhixuedong
     * @date 2021/1/25/025
     */
    public function createOrder(){
        ini_set('date.timezone','Asia/Shanghai');
        require_once ROOT_PATH."extend/wxpay/lib/WxPay.Api.php";
        require_once ROOT_PATH."extend/wxpay/example/WxPay.NativePay.php";
        require_once ROOT_PATH."extend/wxpay/example/log.php";


        Db::startTrans();
        $common = new Common();
        try {
            $rule = [
                ["list", "require", "请选择票种"],
                ["name", "require", "购票人不能为空"],
                ["mobile", "require", "手机号不能为空"],
                ["pay_type", "require", "请选择支付方式"],
            ];
            $validate = new Validate($rule);
            $value = $this->request->post();

            $thisWechat = Session::get("thisWechat");
            $value['uniacid'] = $thisWechat['id'];
            if (!$validate->check($value)) {
                throw new Exception($validate->getError());
            }

            $name = empty($_POST['name'])?'':$_POST['name'];
            $mobile = empty($_POST['mobile'])?'':$_POST['mobile'];
            $IDcard = empty($_POST['IDcard'])?'':$_POST['IDcard'];
            $remark = empty($_POST['remark'])?'':$_POST['remark'];

            if(!empty($mobile)){
                if(!$common->isMobile($mobile)){
                    throw new Exception("手机号码格式有误");
                }
            }
            $count = empty($_POST['count'])?1:$_POST['count'];
            //查询票种库存
            $where['id'] = $_POST['list'];
            $publicTable = "tickets_tickets";
            $newSql = $common->public_select($publicTable,$where);
            $product = $newSql->find();

            if(empty($product)){
                throw new Exception("商品信息有误");
            }

            if($product['inventory']<=0){
                throw new Exception("票已售完");
            }

            if($product['type']==3){
                if(!$common->setCard($IDcard)){
                    throw new Exception("身份证号码有误");
                }
            }
            //生成核销码
            $order_sn = $this->generateNo();
            //生成订单
            $thisWechat = Session::get("thisWechat");
            $order['uniacid'] = $thisWechat['id'];
            $order['add_id'] = Session::get("id");
            $order['real_pay'] = $product['price']*$count;
            $order['status'] =($_POST['pay_type']==3)?2:1;
            $order['pay_type'] =$_POST['pay_type'];
            $order['is_pay'] =($_POST['pay_type']==3)?2:1;
            $order['total_amount'] = $product['price']*$count;
            $order['order_sn'] = $order_sn;
            $order['addtime'] = time();
            $order['currentDate'] = date("Ymd",time());
            $order['name'] = $name;
            $order['mobile'] = $mobile;
            $order['IDcard'] = $IDcard;
            $order['remark'] = $remark;
            $order['year'] = date("Y",time());
            $order['month'] = date("m",time());

            $orderTable = "tickets_order";
            if(!empty($_POST['order_id'])){
                //获取票的支付状态
                $is_pay = $common->public_select($orderTable,['id'=>$_POST['order_id']])->value("is_pay");
                if($is_pay==1){
                    $order['id'] = $_POST['order_id'];
                }
            }
            $order_id = $common->handle($orderTable,$order);
            $tickets_order_detail = "tickets_order_detail";
            if(!empty($_POST['order_id'])){
                //查询购票信息
                $order_product_where['order_id'] = $order_id;
                $detailId = $common->public_select($tickets_order_detail,$order_product_where)->value("id");
                $order_product['id'] = $detailId;
            }
            //插入票信息
            $order_product['order_id'] = $order_id;
            $order_product['tickets_id'] = $product['id'];
            $order_product['title'] = $product['title'];
            $order_product['thumb'] = $product['thumb'];
            $order_product['type'] = $product['type'];
            $order_product['validity'] = $product['validity'];
            $order_product['price'] = $product['price'];
            $order_product['time_range'] = $product['time_range'];
            $order_product['address'] = $product['address'];
            $order_product['content'] = $product['content'];
            $order_product['count'] = $count;
            $order_product['effective_time'] = empty($_POST['effective_time'])?date("Y-m-d",time()):$_POST['effective_time'];
            $order_product['end_time'] = date("Y-m-d",strtotime("+".$order_product['validity']." day",strtotime($order_product['effective_time'])));
            $order_product['degree'] = $product['degree'];
            $common->handle($tickets_order_detail,$order_product);
            //减库存
            //$common->public_select($publicTable,$where)->setDec("inventory",intval($count));
            //生成订单操作流程
            $ordeLog['order_id'] = $order_id;
            if(!empty($_POST['order_id'])){
                $ordeLog['title'] = "订单提交成功 操作人:管理员【".Session::get("user_name")."】提交订单";
                //插入日志
                $log['remark'] = "管理员【".Session::get("user_name")."】更新订单，核销码【".$order_sn."】,关联id【".$order_id."】" ;
            }else{
                $ordeLog['title'] = "订单更新成功 操作人:管理员【".Session::get("user_name")."】更新订单";
                //插入日志
                $log['remark'] = "管理员【".Session::get("user_name")."】提交订单，核销码【".$order_sn."】,关联id【".$order_id."】" ;
            }

            $ordeLog['remark'] = "核销码:".$order_sn;
            $ordeLog['addtime'] = time();
            $ordeLog['add_id'] = Session::get("id");
            $system_order_log = "tickets_order_log";
            $common->handle($system_order_log,$ordeLog);
            $common->addLog($log);

            switch ($_POST['pay_type']){
                case "1":
                    $notify = new NativePay();
                    $input = new WxPayUnifiedOrder();
                    $input->SetBody($product['title']);
                    $input->SetAttach($product['title']);
                    $input->SetOut_trade_no($order_sn);
                    $input->SetTotal_fee($order['real_pay']*100);
                    $input->SetTime_start(date("YmdHis"));
                    $input->SetTime_expire(date("YmdHis", time() + 600));
                    $input->SetGoods_tag("test");
                    $input->SetNotify_url("http://".$_SERVER['SERVER_NAME']."/tickets/Notify/notify");
                    $input->SetTrade_type("NATIVE");
                    $input->SetProduct_id($product['id']);
                    $result = $notify->GetPayUrl($input);
                    $url2 = $result["code_url"];
                    //生成二维码链接
                    $url2 = "http://".$_SERVER['SERVER_NAME']."/tickets/online/qrcode?data=".$url2;
                    $black['url1'] = $url2;
                    break;
                case "3":
//                    $this->sms($order_sn,$order['mobile']);
                    break;
            }



            $black['code'] = 0;
            $black['msg'] = "操作成功";
            $black['order_id'] = $order_id;
            Db::commit();
        } catch (Exception $e) {
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
            Db::rollback();
        }
        return $black;
    }

    /**
     * 在线购票
     * @return mixed
     * @author zhixuedong
     * @date 2021/1/25/025
     */
    public function index(){
        $common = new Common();
        //查询票类型
        $common = new Common();
        $tickets_type = $common->publicAttribute("tickets_type");
        $this->assign("tickets_type",$tickets_type);

        //平台支付方式
        $paytype_table = "paytype";
        $where['status'] = 1;
        $field="id,name";
        $paytype = $common->public_select($paytype_table,$where,$field)->select();
        $this->assign("paytype",$paytype);

        $list = $this->selList($common,1);
        $this->assign("list",$list);

        //获取当天日期
        $newtime = date("Y-m-d");
        $this->assign("newtime",$newtime);
        return $this->fetch('index');
    }


    public function selList($common,$type){
        //票列表
        $thisWechat = Session::get("thisWechat");
        if(!empty($type)){
            $where['type'] = $type;
        }
        $where['uniacid'] = $thisWechat['id'];
        $where['status'] = 1;
        $publicTable = "tickets_tickets";
        $field="id,title,thumb,type,price,inventory,soldout";
        $newSql = $common->public_select($publicTable,$where,$field);
        $list = $newSql->order("sort desc,id desc")->select();
        return $list;
    }


    /**
     * 票详情
     * @return false|string
     * @author zhixuedong
     * @date 2021/1/21/021
     */
    public function detailApi(){
        $common = new Common();
        try {
            $where['id'] = $_POST['id'];
            $publicTable = "tickets_tickets";
            $field="id,title,thumb,type,price,inventory,soldout,validity,degree,time_range,address,content";
            $newSql = $common->public_select($publicTable,$where,$field);
            $detail = $newSql->order("sort desc,id desc")->find();
            $tickets_type = $common->publicAttribute("tickets_type");
            $detail['type'] = $tickets_type[$detail['type']];
            $black['code'] = 0;
            $black['data'] = $detail;
        } catch (Exception $e) {
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return $black;
    }

    /**
     * 获取列表
     * @author zhixuedong
     * @date 2021/1/21/021
     */
    public function listsApi(){
        $common = new Common();
        try {
            $type = empty($_POST['type'])?1:$_POST['type'];
            $list = $this->selList($common,$type);
            $black['code'] = 0;
            $black['data'] = $list;
        } catch (Exception $e) {
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return $black;
    }




}